package com.zl.ribbon.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zl.ribbon.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @Author : archer
 * @Date :  2020/7/17
 * @Description : 服务类
 * @Version : 1.0
 */
@Service
public class RibbonService {

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiServiceFallBack")
    public String hiService(){
        return restTemplate.getForObject("http://service01/user/find",String.class);
    }

    public String hiServiceFallBack(){
        return "抱歉，网络开小差了，请刷新";
    }


    public String hiService2Post(User user){

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        param.add("id", user.getId());
        param.add("name", user.getName());

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<MultiValueMap<String, Object>> formEntity =
                new HttpEntity<MultiValueMap<String, Object>>(param, headers);

        //含有请求头
        String result = restTemplate.postForObject("http://service-hi/hi", formEntity, String.class);

        return result;
    }
}
